package com.spsy.order.controller;

/**
 * @author: liuzhiping
 * @date: 2025/5/16 16:47
 **/

import com.spsy.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: liuzhiping
 * @date: 2025/5/5 11:40
 **/
@Slf4j
@RestController
@RequestMapping("/order")
public class LockController {


    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RedisTemplate redisTemplate;

    //全局共享，共享支援
    private static  int i  =  0;


    private ReentrantLock reentrantLock = new ReentrantLock();




    //100请求 ，同时并发请求  只能解决单个虚拟机的问题。
    @GetMapping("/lock1")
    public R   addUserCart1(String userId) throws Exception{
        reentrantLock.lock();
        try {
           // i = i + 1;
            int i= (int)this.redisTemplate.opsForValue().get("abc");
            i = i+1;
            this.redisTemplate.opsForValue().set("abc",i);

        }finally {
            reentrantLock.unlock();;
        }

        return  R.ok();
    }


    @GetMapping("/lock2")
    public R addUserCart2( String userId) throws Exception{

        i = i+1;
        System.out.println("-------ffffff丽清");
        System.out.println("----aeiwriwqer保祥");
        return  R.ok();
    }




        /***
         * 处理用户购物车的逻添加
         * @return
         * @throws Exception
         */
    @GetMapping("/lock")
    public R addUserCart(@RequestParam("userId") String userId) throws Exception{


        //保祥：userId=102

        //周丽清 userId = 103  还有10000个人，他们也要处理自己购物车的逻辑

        //10002  同时执行

        //String lockKey = "order::"+userId;

        //非共享资源
        Counter counter = new Counter();


        String productId = "100001";
        String lockKey = productId;



        //key非常关键 锁的力度 10002
        RLock rLock = this.redissonClient.getLock(lockKey);



        try{

            //锁住共享资源的操作：修改 102  10001等等
             boolean boo = rLock.tryLock(2,5, TimeUnit.SECONDS);

             if(boo){//true
                 log.info("=========执行业务逻辑,睡4秒 lockKey:{}",lockKey);
                 //是用购物车处理的逻辑
                 //Thread.sleep(900000000);

                 //实现逻辑的执行时间要超过5秒。

                 //？？？？？

            /*     什么东西加锁。？？？？
                 什么东西要加分布式锁？？？*/




             }else{
                 return  R.ok("资源已经被锁了，执行不了");
             }

        }catch (Exception e){
            e.printStackTrace();

        }finally {
            /****
             * 19:41:42.062 [http-nio-9802-exec-8] ERROR c.s.c.s.h.GlobalExceptionHandler - [handleRuntimeException,112] - 请求地址'/order/lock',发生未知异常.
             * java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node id: 6783492c-5cf9-4e82-9840-a81302377258 thread-id: 238
             * 	at org.redisson.RedissonBaseLock.lambda$unlockAsync0$2(RedissonBaseLock.java:290)
             * 	at java.base/java.util.concurrent.CompletableFuture.uniHandle(CompletableFuture.java:934)
             * 	at java.base/java.util.concurrent.CompletableFuture$UniHandle.tryFire(CompletableFuture.java:911)
             */
            if (rLock.isLocked() && rLock.isHeldByCurrentThread()) {
                rLock.unlock();
            }
        }

        return R.ok();

    }



    public class Counter {
        private int i = 0;

        public void increment() {
            i = i + 1; //
        }

        public int getValue() {
            return i;
        }
    }

}
